#!/bin/bash

# Clean script for image2pcd project
# This script will clean up build artifacts and generated files

set -e # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Project root directory (parent of scripts directory)
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BUILD_DIR="$PROJECT_DIR/build"

echo -e "${BLUE}=== Cleaning image2pcd project ===${NC}"

# Function to remove file/directory if it exists
remove_if_exists() {
    if [ -e "$1" ]; then
        echo -e "${YELLOW}Removing: $1${NC}"
        rm -rf "$1"
    fi
}

# Clean build directory
if [ -d "$BUILD_DIR" ]; then
    echo -e "${YELLOW}Cleaning build directory...${NC}"
    rm -rf "$BUILD_DIR"
    echo -e "${GREEN}✓ Build directory cleaned${NC}"
else
    echo -e "${GREEN}✓ Build directory already clean${NC}"
fi

# Remove main executable
remove_if_exists "$PROJECT_DIR/image2pcd"

# Remove generated files in test_data directory (but preserve input files)
echo -e "${YELLOW}Cleaning generated files in test_data...${NC}"
find "$PROJECT_DIR/test_data" -name "*.pcd" -type f -exec rm -f {} \; 2>/dev/null || true
find "$PROJECT_DIR/test_data" -name "*.jpg" -type f -exec rm -f {} \; 2>/dev/null || true
# Remove PNG files but exclude LocationImg directories (input files)
find "$PROJECT_DIR/test_data" -name "*.png" -type f ! -path "*/LocationImg/*" -exec rm -f {} \; 2>/dev/null || true
# Remove map_only23456.txt file
remove_if_exists "$PROJECT_DIR/test_data/map_only23456.txt"
echo -e "${GREEN}✓ Preserved PNG input files in LocationImg directories${NC}"

# Remove web visualization output
remove_if_exists "$PROJECT_DIR/web_visualization"

# Remove any Python cache files
find "$PROJECT_DIR" -name "__pycache__" -type d -exec rm -rf {} \; 2>/dev/null || true
find "$PROJECT_DIR" -name "*.pyc" -type f -exec rm -f {} \; 2>/dev/null || true

# Remove common temporary and backup files
find "$PROJECT_DIR" -name "*~" -type f -exec rm -f {} \; 2>/dev/null || true
find "$PROJECT_DIR" -name "*.bak" -type f -exec rm -f {} \; 2>/dev/null || true
find "$PROJECT_DIR" -name "*.tmp" -type f -exec rm -f {} \; 2>/dev/null || true

# Remove any core dumps
find "$PROJECT_DIR" -name "core" -type f -exec rm -f {} \; 2>/dev/null || true
find "$PROJECT_DIR" -name "core.*" -type f -exec rm -f {} \; 2>/dev/null || true

echo -e "${GREEN}=== Cleanup Complete ===${NC}"
echo -e "${GREEN}All build artifacts and generated files have been removed${NC}"
